package sample.positive.service;

import java.util.*;

/**
 * 支付工厂
 */
public class PaymentFactory {

    private static final Map<String, Payment> paymentMap = new HashMap<>();

    static {
        try {
            // 通过反射获取所有实现 Payment 接口的实现类
            List<Class<?>> implementations = findImplementations("sample.positie.service.impl", Payment.class);
            for(Class<?> clazz : implementations){
                Payment payment = (Payment) clazz.newInstance();
                paymentMap.put(payment.paymentType(), payment);
            }
        }
        catch (Exception ex){
            // 错误处理
        }
    }

    /**
     * 根据支付类型获取支付实例
     * @param paymentType
     * @return
     */
    public static Payment getPayment(String paymentType) {
        Payment payment = paymentMap.get(paymentType);
        if(payment == null){
            throw new UnsupportedOperationException("Unsupported payment type: " + paymentType);
        }
        return payment;
    }

    /**
     * 获取实现 Payment 接口的所有实现类
     * @param packageName
     * @param interfaceClass
     * @return
     * @throws ClassNotFoundException
     */
    private static List<Class<?>> findImplementations(String packageName, Class<Payment> interfaceClass) throws ClassNotFoundException {
        List<Class<?>> implementations = new ArrayList<>();

        // 这里应该替换为实际的类路径扫描逻辑
        // 以下代码仅作示例，实际上你需要使用某种方式来获取包下所有类
        for (String className : getClassNamesInPackage(packageName)) {
            Class<?> clazz = Class.forName(className);
            if (interfaceClass.isAssignableFrom(clazz) && !clazz.equals(interfaceClass)) {
                implementations.add(clazz);
            }
        }
        return implementations;
    }

    // 模拟获取包下所有类的方法
    private static List<String> getClassNamesInPackage(String packageName) {
        // 这里应该实现真实的类路径扫描逻辑
        // 返回一个字符串列表，每个元素代表包中的一个类的全限定名
        // 示例返回值
        return Arrays.asList("sample.positie.service.impl.AlipayPayment",
                "sample.positie.service.impl.CreditCardPayment");
    }
}
